﻿Public Class WpfUtil
    Public Shared Function FindAncestorOfType(Of T As DependencyObject)(source As DependencyObject) As T
        Dim currentObject As DependencyObject = VisualTreeHelper.GetParent(source)
        Do Until currentObject Is Nothing OrElse TypeOf currentObject Is T
            currentObject = VisualTreeHelper.GetParent(currentObject)
        Loop
        Return CType(currentObject, T)
    End Function

    'Public Shared Function FindDescendantOfType(Of T As DependencyObject)(source As DependencyObject) As T
    '    Dim foundElement As T = Nothing
    '    If TypeOf source Is FrameworkElement Then
    '        TryCast(source, FrameworkElement).ApplyTemplate()
    '    End If
    '    For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(source) - 1
    '        Dim visual As Visual = TryCast(VisualTreeHelper.GetChild(source, i), Visual)
    '        foundElement = FindDescendantOfType(Of T)(visual)
    '        If foundElement IsNot Nothing Then
    '            Exit For
    '        End If
    '    Next
    '    Return foundElement
    'End Function

    Public Shared Function FindVisualChildByName(Of T As DependencyObject)(parent As DependencyObject, name As String) As T
        For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(parent) - 1
            Dim child As DependencyObject = VisualTreeHelper.GetChild(parent, i)
            Dim controlName As String = TryCast(child.GetValue(Control.NameProperty), String)
            If controlName = name Then
                Return TryCast(child, T)
            Else
                Dim result As T = FindVisualChildByName(Of T)(child, name)
                If result IsNot Nothing Then
                    Return result
                End If
            End If
        Next
        Return Nothing
    End Function
End Class
